package com.colter.project.sample.jedis;

import java.util.List;
import java.util.UUID;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.Response;
import redis.clients.jedis.Transaction;

public class RedisLock {
	private Jedis jedis;

	public RedisLock() {
		JedisClient client = new JedisClient();
		jedis = client.getJedis();
	}

	public String getSimpleLock(String lockName) {
		String uuid = UUID.randomUUID().toString();
		jedis.watch(lockName);
		Transaction tx = jedis.multi();
		Response<Long> res = tx.setnx(lockName, uuid);
		List<Object> obj = tx.exec();
		jedis.unwatch();
		if (obj.size() != 0 && res.get() == 1)
			return uuid;
		else
			return null;
	}

	public boolean releaseLock(String lockName, String identifier) {
		if (identifier == null)
			return false;
		
		jedis.watch(lockName);
		if (identifier.equals(jedis.get(lockName))) {

			Transaction ta = jedis.multi();
			Response<Long> res = ta.del(lockName);
			List<Object> obj = ta.exec();
			jedis.unwatch();
			return obj.size() != 0 && res.get() == 1;
		}
		
		jedis.unwatch();
		return false;
	}

	public static void main(String[] args) {
		RedisLock rl = new RedisLock();
		String id = rl.getSimpleLock("test2");
		System.out.println(id);

		boolean flag2 = rl.releaseLock("test2", "be6d899f-8679-417f-ac17-001a06bd724c");
		System.out.println(flag2);
	}

}
